const fs = require("fs");
const exec = require('await-exec')
const path = require("path");
const config = require('./config');
// var execs = require('child_process').exec;
let finishStart = 0;
let finishStarted = 0;
let appZsyncUrl = "";
const type = config.type;

function getCurrentBuild () {
  const localDataPath = path.join(__dirname, "localData");
  if (!fs.existsSync(localDataPath)) {
    fs.mkdirSync(localDataPath);
  }
  return fs.readFileSync(path.resolve(__dirname, "./localData/currentBuildNumber.txt"), "utf8");
}

function saveCurrentBuild (number) {
  const localDataPath = path.join(__dirname, "localData");
  if (!fs.existsSync(localDataPath)) {
    fs.mkdirSync(localDataPath);
  }
  fs.writeFileSync(path.resolve(__dirname, "./localData/currentBuildNumber.txt"), number + "");
}
const password = config.password
async function execShell (appSh, appPkg, siotSh, siotPkg, lastSuccessfulBuild) {
  await execStopServiceShellData()
  let state = await execInstallShellData(appSh, appPkg, siotSh, siotPkg, lastSuccessfulBuild)
  if (state) await execStartServiceShellData();
  await checkState(lastSuccessfulBuild);
}
async function execStopServiceShellData () {

  let stopServiceShellData = 'echo "' + password + '" | sudo -S systemctl stop linksdk siot_run kws_run redis'
  console.log(stopServiceShellData);
  console.log(" ")
  try { await exec(stopServiceShellData) } catch (e) { }
  console.log("rm -rf /home/respeaker/work/ && mv /home/respeaker/check_px_build1/pkg/* /home/respeaker/ && chmod +x /home/respeaker/install_app_pkg.sh && chmod +x /home/respeaker/install_sdk_pkg.sh");
  console.log(" ")
  try {
    await exec("rm -rf /home/respeaker/work/")
  } catch (e) { }
  try {
    await exec("mv /home/respeaker/check_px_build1/pkg/* /home/respeaker/")
  } catch (e) { }
  try {
    await exec("chmod +x /home/respeaker/install_app_pkg.sh")
  } catch (e) { }
  try {
    await exec("chmod +x /home/respeaker/install_sdk_pkg.sh")
  } catch (e) { }




  async function checkState (lastSuccessfulBuild) {
    if (finishStart == 4 && finishStarted == 4) {
      console.log("---------------------自动测试通过---------------------")
      saveCurrentBuild(lastSuccessfulBuild)
      await exec('curl -u wangxiaotang:Abcd1234!   --data-urlencode "description=' + '自动测试通过(' + lastSuccessfulBuild + ')' + '，' + parseTime(new Date().getTime()) + '" \
    --data-urlencode "Submit=Submit" \
    "https://test-app.stc-seedland.com.cn/job/px/' + lastSuccessfulBuild + '/submitDescription"')
      await getZsyncInfo(lastSuccessfulBuild)

      console.log(" ")
      console.log(" ")
    } else if (finishStart == 4 && finishStarted != 4) {
      let info = (!redis ? "redis," : "") + (!kws_run ? "kws_run," : "") + (!siot_run ? "siot_run," : "") + (!linksdk ? "linksdk," : "")
      info = info ? info.substring(0, info.length - 1) : "";
      info = info ? "（" + info + "）" : "";
      console.log("--------------------部分服务启动失败，自动测试未通过---------------------")
      await exec('curl -u wangxiaotang:Abcd1234!   --data-urlencode "description=' + '部分服务启动失败，自动测试未通过' + info + '，' + parseTime(new Date().getTime()) + '" \
        --data-urlencode "Submit=Submit" \
        "https://test-app.stc-seedland.com.cn/job/px/' + lastSuccessfulBuild + '/submitDescription"')

      console.log(" ")
      console.log(" ")
    }
  }
  let redis = false;
  let linksdk = false;
  let kws_run = false;
  let siot_run = false;
  async function execStartServiceShellData () {
    finishStart = 0;
    finishStarted = 0;
    redis = false;
    linksdk = false;
    kws_run = false;
    siot_run = false;

    console.log('echo "' + password + '" | sudo -S systemctl restart redis')
    console.log("systemctl status redis")
    try { await exec('echo "' + password + '" | sudo -S systemctl restart redis') } catch (e) { };
    try {
      let result = await exec("systemctl status redis");
      if (result.stdout.indexOf("Active: active (running)") > -1) {
        redis = true;
        console.log("redis started");
        finishStart++;
        finishStarted++;
      } else {
        console.log("redis not started");
        finishStart++;
      }
    } catch (e) {
      console.log("redis not started");
      finishStart++;
    }
    console.log('echo "' + password + '" | sudo -S systemctl restart linksdk')
    console.log("systemctl status linksdk")
    try { await exec('echo "' + password + '" | sudo -S systemctl restart linksdk') } catch (e) { };
    try {
      let result = await exec('echo "' + password + '" | sudo -S systemctl restart linksdk');
      if (result.stdout.indexOf("Active: active (running)") > -1) {
        linksdk = true;
        console.log("linksdk started");
        finishStart++;
        finishStarted++;
      } else {
        console.log("linksdk not started");
        finishStart++;
      }
    } catch (e) {
      console.log("linksdk not started");
      finishStart++;
    }
    console.log('echo "' + password + '" | sudo -S systemctl restart kws_run')
    console.log("systemctl status kws_run")
    try { await exec('echo "' + password + '" | sudo -S systemctl restart kws_run') } catch (e) { };
    try {
      let result = await exec('echo "' + password + '" | sudo -S systemctl restart kws_run');
      if (result.stdout.indexOf("Active: active (running)") > -1) {
        kws_run = true;
        console.log("kws_run started");
        finishStart++;
        finishStarted++;
      } else {
        console.log("kws_run not started");
        finishStart++;
      }
    } catch (e) {
      console.log("kws_run not started");
      finishStart++;
    }
    console.log('echo "' + password + '" | sudo -S systemctl restart siot_run')
    console.log("systemctl status siot_run")
    try { await exec('echo "' + password + '" | sudo -S systemctl restart siot_run') } catch (e) { };
    try {
      let result = await exec('echo "' + password + '" | sudo -S systemctl restart siot_run');
      if (result.stdout.indexOf("Active: active (running)") > -1) {
        siot_run = true;
        console.log("siot_run started");
        finishStart++;
        finishStarted++;
      } else {
        console.log("siot_run not started");
        finishStart++;
      }
    } catch (e) {
      console.log("siot_run not started");
      finishStart++;
    }


  }
  async function execInstallShellData (appSh, appPkg, siotSh, siotPkg, lastSuccessfulBuild) {
    console.log('/home/respeaker/' + appSh + " /home/respeaker/" + appPkg)
    console.log(" ")
    try {
      await exec('/home/respeaker/' + appSh + " /home/respeaker/" + appPkg)
    } catch (e) {
      console.log("app安装失败", e)
      await sendState("app安装失败", lastSuccessfulBuild)
      return false;
    }
    console.log('/home/respeaker/' + siotSh + " /home/respeaker/" + siotPkg)
    console.log(" ")
    try {
      await exec('/home/respeaker/' + siotSh + " /home/respeaker/" + siotPkg)
      return true;
    } catch (e) {
      console.log("siot安装失败", e)
      await sendState("siot安装失败", lastSuccessfulBuild)
      return false;
    }
  }


  async function sendState (info, lastSuccessfulBuild) {
    exec('curl -u wangxiaotang:Abcd1234!   --data-urlencode "description=' + info + '，' + parseTime(new Date().getTime()) + '" \
  --data-urlencode "Submit=Submit" \
  "https://test-app.stc-seedland.com.cn/job/px/' + lastSuccessfulBuild + '/submitDescription"')
  }
  function parseTime (time) {
    if (time) {
      let date = new Date(time);
      let month =
        date.getMonth() + 1 < 10 ?
          "0" + (date.getMonth() + 1) :
          date.getMonth() + 1;
      let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hours =
        date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let minutes =
        date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let seconds =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
    } else {
      return "";
    }
  }

  function setZsyncUrl (app) {
    appZsyncUrl = config.pxLastBuildPkgDownloadUrl + app;
  }

  async function getZsyncInfo (lastSuccessfulBuild) {
    const responseData = await superagent
      .get("https://test-app.stc-seedland.com.cn/job/px/" + (parseInt(lastSuccessfulBuild) - 1) + "/api/json")
      .then(resp => resp.body)
      .catch(e => {
        return null;
      })
    if (responseData) {
      if (type == "M1") {
        appZsyncFileName = getAppPkgZsync(responseData.artifacts, "M1")
      } else {
        appZsyncFileName = getAppPkgZsync(responseData.artifacts, "M2")
      }
      let beforeAppZsyncUrl = "https://test-app.stc-seedland.com.cn/job/px/" + (parseInt(lastSuccessfulBuild) - 1) + "/artifact/work/app/dist/" + appZsyncFileName;
      console.log("获取ota升级信息中。。。")
      let result = await exec('bash /home/respeaker/check_px_build/zsyncdelta.sh ' + appZsyncUrl + " " + beforeAppZsyncUrl)
      if (result.stdout) {
        let split = result.stdout.split("fetched");
        let otaData = split[split.length - 1];
        console.log("otaData", otaData)
        if (otaData) {
          await exec('curl -u wangxiaotang:Abcd1234!   --data-urlencode "description=' + '自动测试通过(增量更新流量:' + otaData + 'bytes)，' + parseTime(new Date().getTime()) + '" \
          --data-urlencode "Submit=Submit" \
          "https://test-app.stc-seedland.com.cn/job/px/' + lastSuccessfulBuild + '/submitDescription"')
        }
      }
    }
  }

  function getAppPkgZsync (artifacts, type) {
    for (let i in artifacts) {
      if (artifacts[i].fileName.indexOf(type) > -1 && artifacts[i].fileName.indexOf(".tar.zsync") > -1) {
        return artifacts[i].fileName;
      }
    }

  }


  exports.getCurrentBuild = getCurrentBuild;
  exports.saveCurrentBuild = saveCurrentBuild;
  exports.execStopServiceShellData = execStopServiceShellData;
  exports.execInstallShellData = execInstallShellData;
  exports.execStartServiceShellData = execStartServiceShellData;
  exports.parseTime = parseTime;
  exports.sendState = sendState;
  exports.setZsyncUrl = setZsyncUrl;
  exports.getAppPkgZsync = getAppPkgZsync;
  exports.execShell = execShell;
